package com.shinow.capacitor.plusins.printer.zebra;

import androidx.appcompat.app.AppCompatActivity;

import java.util.HashMap;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ZplTransferred {
    private static final String REGEX = "(\\^FW([NRIB]))*\\^CF([A-Za-z0-9])\\,([0-9]+)\\^FD([^\\^]+)\\^FS";
    private static final HashMap<String, Float> ROTATE_CONTRAST = new HashMap<String, Float>() {{
        this.put("N", 0F);
        this.put("R", 90F);
        this.put("I", 180F);
        this.put("B", 270F);
    }};

    private interface RegexCallBack {
        String callback(Matcher matcher);
    }

    private static String replaceAll(String str, RegexCallBack regexCallBack) {
        StringBuffer stringBuffer = new StringBuffer();

        Pattern pattern = Pattern.compile(REGEX);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            matcher.appendReplacement(stringBuffer, regexCallBack.callback(matcher));
        }
        matcher.appendTail(stringBuffer);

        return stringBuffer.toString();
    }

    public static String execute(AppCompatActivity Activity, String zpl) {
        return replaceAll(zpl, (matcher) -> ImageTransferredZpl.transformationImage(FontCompoundImage.createImage(matcher.group(5), Integer.parseInt(Objects.requireNonNull(matcher.group(4))), matcher.group(1) != null ? Objects.requireNonNull(ROTATE_CONTRAST.get(matcher.group(2))) : 0f)));
    }
}
